package com.shelpe.services.tenant.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.shelpe.services.tenant.mongomodel.SimbadTask;
import com.shelpe.services.tenant.mongorepository.SimbadTaskRepository;

@RestController
@RequestMapping(value="/jobserver")
public class JobController {

	private static final Logger logger = LoggerFactory.getLogger(JobController.class);
	
	@Autowired
	private SimbadTaskRepository taskRep;

	
	@RequestMapping("/jobsbuilder")
	@ResponseBody
	public boolean jobBuilder(@RequestParam("serviceid") String serviceId, @RequestParam("taskid") String taskId, 
			@RequestParam("freq") Long freq, @RequestParam(value = "last_time", required = false) String lastTime){
		
		SimbadTask task = new SimbadTask();
		task.setId(serviceId+taskId);
		task.setServiceId(serviceId);
		task.setTaskId(taskId);
		task.setFreq(freq);
		task.setCreateTime(new Date());
		String lastStr = "1970-01-01 00:00:00";
		if(lastTime != null){
			lastStr = lastTime;
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			task.setLastTime(sdf.parse(lastStr));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info(">>> jobBuilder taskId {}, freq {}", taskId, freq);
		taskRep.save(task);
		
		return true;
	}
}
